package com.ferry.example.spring;

import com.alibaba.fastjson.JSON;
import com.ferry.protocol.payload.RequestPayload;
import com.ferry.protocol.payload.ResponsePayload;
import com.ferry.registry.domain.service.ServiceMetaData;
import com.ferry.serial.api.Serializer;
import com.ferry.serial.api.SerializerFactory;
import com.ferry.serial.api.SerializerType;
import com.ferry.transport.netty.provider.MessageWrapper;
import com.ferry.transport.netty.provider.RespWrapper;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    //通道就绪事件
    public void channelActive(ChannelHandlerContext ctx){

        write(ctx);

    }

    private void write(ChannelHandlerContext ctx) {
        System.out.println("NettyClientHandler1");
        Channel channel = ctx.channel();
        RequestPayload request = new RequestPayload();

        MessageWrapper messageWrapper = new MessageWrapper();
        //messageWrapper.setServiceMetaData();
        messageWrapper.setAppName("ferry");
        messageWrapper.setMethodName("getUserName");
        messageWrapper.setArgs(null);

        ServiceMetaData serviceMetaData = new ServiceMetaData("ferry", "UserService", "1.0");
        messageWrapper.setServiceMetaData(serviceMetaData);

        Serializer serializer = SerializerFactory.getSerializer(SerializerType.HESSIAN.getCode());
        byte[] bytes = serializer.writeObject(messageWrapper);

        request.bytes(SerializerType.HESSIAN.getCode(), bytes);

        ctx.writeAndFlush(request);
    }

    //读取数据事件
    public void channelRead(ChannelHandlerContext ctx,Object msg){
        ResponsePayload responsePayload = (ResponsePayload) msg;
        byte serializerCode = responsePayload.serializerCode();
        Serializer serializer = SerializerFactory.getSerializer(serializerCode);
        RespWrapper respWrapper = serializer.readObject(responsePayload.bytes(), RespWrapper.class);
        System.out.println(JSON.toJSONString(respWrapper));
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        ctx.channel().close();
    }
}